﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KpiConfigProject.DataBase;
using MySql.Data.MySqlClient;

namespace KpiConfigProject.Manager
{
    public class DrillMenuManager : AbstractManager
    {
        public override string GetSQL()
        {
            return "select * from ctbDrillMenu";
        }

        public DataTable GetList()
        {
            return base.GetList(GetSQL());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public Dictionary<int, List<DataRow>> GetGroupDictionary()
        {
            DataTable table = base.GetList(GetSQL());
            Dictionary<int, List<DataRow>> groupDic = new Dictionary<int, List<DataRow>>();
            foreach (DataRow row in table.Rows)
            {
                int groupId = int.Parse(row[2].ToString());
                if (groupDic.ContainsKey(groupId))
                {
                    groupDic[groupId].Add(row);
                }
                else
                {
                    List<DataRow> rowList = new List<DataRow>();
                    rowList.Add(row);
                    groupDic.Add(groupId, rowList);
                }
            }
            return groupDic;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="kpiList"></param>
        /// <returns></returns>
        public bool InsertData(int drillId, List<int> menuList)
        {
            MySqlTransaction transaction = null;
            try
            {
                DataTable table = GetList();
                int rowCount = table.Rows.Count;
                int maxGroupId = rowCount <= 0 ? 0 : int.Parse(table.Rows[rowCount - 1][0].ToString());
                DataBaseManager.ExecuteNonSql("delete from ctbDrillMenu where intDrillId = " + drillId);
                MySqlCommand cmd = new MySqlCommand("", DataBaseManager.GetConnection());
                transaction = DataBaseManager.GetConnection().BeginTransaction();
                for (int i = 0; i < menuList.Count; i++)
                {
                    maxGroupId += i + 1;
                    cmd.CommandText = "insert into ctbDrillMenu (intDrillId,intMenuId) " +
                                      "values (" + drillId + "," + menuList[i] + ") ";
                    cmd.ExecuteNonQuery();
                }
                transaction.Commit();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                if (transaction != null)
                    transaction.Rollback();
            }
            return false;
        }
    }
}
